/* 
封装一个axios请求 
返回值为：异步返回的数据是：response.data
*/

import axios from 'axios'
export default (url, data = {}, type = 'GET')=> {
    return new Promise(function (resolve, reject) {
        // 执行ajax 异步请求
        let promise
        if (type === 'GET') {
            // 准备URL参数数据
            let dataStr = '' //数据拼接字符串
            Object.keys(data).forEach(key => {
                dataStr += key + '=' + data[key] + '&'
            })
            if (dataStr !== '') {
                /* 截取字符串 */
                dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
                url = url + '?' + dataStr
            }
            //发起get请求 
            promise = axios.get(url)
        }
        else {
            promise = axios.post(url, data)
        }
        promise.then(response => {
            resolve(response.data)
        }).catch(err => {
            reject(err)
        })
    })
}
